using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Lzfy_Refund_Service.Services
{
    /// <summary>
    /// 门诊患者就诊信息同步定时任务
    /// </summary>
    public class OutpPatientVisitSyncTask : BackgroundService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<OutpPatientVisitSyncTask> _logger;
        private readonly IConfiguration _configuration;
        private readonly TimeSpan _interval;

        public OutpPatientVisitSyncTask(
            IServiceProvider serviceProvider,
            ILogger<OutpPatientVisitSyncTask> logger,
            IConfiguration configuration)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
            _configuration = configuration;

            var intervalSeconds = _configuration.GetValue<int>("OutpPatientVisitTask:IntervalSeconds", 10);
            _interval = TimeSpan.FromSeconds(intervalSeconds);
            
            _logger.LogInformation("门诊患者就诊信息同步定时任务已初始化，执行间隔: {Interval} 秒", intervalSeconds);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("门诊患者就诊信息同步定时任务开始运行");
            
            // 等待5秒后开始执行，避免应用启动时的资源竞争
            await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
            
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    await ExecuteSyncTask();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "门诊患者就诊信息同步任务执行异常");
                }
                
                try
                {
                    await Task.Delay(_interval, stoppingToken);
                }
                catch (OperationCanceledException)
                {
                    // 正常的取消操作，退出循环
                    break;
                }
            }
            
            _logger.LogInformation("门诊患者就诊信息同步定时任务已停止");
        }

        private async Task ExecuteSyncTask()
        {
            using var scope = _serviceProvider.CreateScope();
            var outpPatientVisitService = scope.ServiceProvider.GetRequiredService<IOutpPatientVisitService>();
            
            try
            {
                _logger.LogDebug("开始执行门诊患者就诊信息同步任务");
                
                var syncedCount = await outpPatientVisitService.SyncRecentOutpPatientVisitsToRedisAsync();
                
                if (syncedCount > 0)
                {
                    _logger.LogInformation("门诊患者就诊信息同步任务完成，同步了 {Count} 条新数据", syncedCount);
                }
                else
                {
                    _logger.LogDebug("门诊患者就诊信息同步任务完成，没有新数据需要同步");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行门诊患者就诊信息同步任务时发生异常");
            }
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("正在停止门诊患者就诊信息同步定时任务...");
            await base.StopAsync(cancellationToken);
            _logger.LogInformation("门诊患者就诊信息同步定时任务已停止");
        }
    }
}